// 云函数入口文件
const cloud = require('wx-server-sdk');
const axios = require('axios');
//解密的工具：可以把豆瓣加密的图书解密出图书信息 yarn add douban --save
const doubanbook = require('doubanbook');
//解析获取的html内容  yarn add cheerio --save
const cheerio = require('cheerio');


cloud.init();

//https://search.douban.com/book/subject_search?search_text=9787010009247

async function searchDouban(isbn) {
  const url = 'https://search.douban.com/book/subject_search?search_text=' + isbn
  const searchInfo = await axios.get(url)
//  正则表达式提取豆瓣加密的信息
  let reg = /window\.__DATA__ = "(.*)"/
  if (reg.test(searchInfo.data)) {
    let searchData = doubanbook(RegExp.$1)[0]
    return searchData
  }
}

async function getDouban(isbn) {
  let detailInfo = await searchDouban(isbn);

  //获取书籍详情信息
  const detailPage = await axios.get(detailInfo.url);
  const $ = cheerio.load(detailPage.data);
  const info = $('#info').text().split('\n').map(v => v.trim()).filter(v => v);
  //分类 tags
  //价格price
  //出版社  publisher
  //作者  author
  let author = info[1];
  let publisher, price;
  info.forEach(v => {
    let temp = v.split(':');
    if (temp[0] === '出版社') {
      publisher = temp[1]
    }
    if (temp[0] === '定价') {
      price = temp[1]
    }
  });
  let tags = [];
  $('#db-tags-section a.tag').each((i, v) => {
    tags.push({
      title: $(v).text()
    })
  })


  const ret = {
    tags,
    author,
    publisher,
    price,
    image: detailInfo.cover_url,
    rate: detailInfo.rating.value,
    alt: detailInfo.url,
    title: detailInfo.title,
    summary: $('#link-report .intro').text()
  }
  console.log('ret', ret);
  return ret
}

// getDouban(9787508051000);

// 云函数入口函数
exports.main = async (event, context) => {
  const {isbn} = event;
  if (isbn) {
    return getDouban(isbn)

  } else {
    return {
      code: -1,
      msg: '请扫描的图书码'

    }
  }
}
